<?php

namespace App\Exception\Handler;

use App\Exception\PermissionException;
use Swoft\Error\Annotation\Mapping\ExceptionHandler;
use Swoft\Http\Message\ContentType;
use Swoft\Http\Message\Response;
use Swoft\Http\Server\Exception\Handler\AbstractHttpErrorHandler;
use Throwable;

/**
 * Class PermissionExceptionHandler
 * @package App\Exception\Handler
 * @ExceptionHandler(PermissionException::class)
 */
class PermissionExceptionHandler extends AbstractHttpErrorHandler
{

    /**
     * @inheritDoc
     */
    public function handle(Throwable $e, Response $response): Response
    {
        // TODO 需要根据 errorCode 和 errorMsg 进行统一返回
        $data = [
            'status' => 400,
            'error_code' => $e->getCode(),
            'error_user_title' => '异常',
            'error_user_msg' => '权限异常!',
            'message' => $e->getMessage(),
        ];

        return $response->withHeader('Access-Control-Allow-Origin', '*')
            ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
            ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS')
            ->withContentType(ContentType::JSON)->withData($data);
    }
}
